<!-- 管理后台仪表板页面 - 显示系统统计数据和快速操作入口 -->
<template>
    <div class="dashboard">
        <!-- 示例数据提示 -->
        <el-alert
            v-if="isUsingSampleData"
            title="当前显示的是示例数据"
            description="由于后端API暂时不可用，正在显示示例数据。实际数据将在后端服务可用时自动加载。"
            type="info"
            :closable="false"
            show-icon
            class="sample-data-notice"
        />
        
        <!-- 统计卡片区域 - 显示关键数据指标 -->
        <div class="stats-grid" v-loading="isLoading">
            <div class="stat-card" v-for="stat in statistics" :key="stat.title">
                <!-- 统计图标，使用动态背景色 -->
                <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                    <el-icon>
                        <component :is="stat.icon" />
                    </el-icon>
                </div>
                <!-- 统计内容区域 -->
                <div class="stat-content">
                    <h3 class="stat-title">{{ stat.title }}</h3>
                    <p class="stat-value">{{ stat.value }}</p>
                    <!-- 变化趋势，支持上升/下降指示 -->
                    <p class="stat-change" :class="stat.trend">
                        {{ stat.change }}
                        <el-icon>
                            <component :is="stat.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
                        </el-icon>
                    </p>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 - 包含最近文章和快速操作 -->
        <div class="dashboard-content">
            <!-- 最近文章列表 -->
            <div class="recent-posts">
                <div class="section-header">
                    <h2>最近文章</h2>
                    <router-link to="/admin/posts" class="view-all">查看全部</router-link>
                </div>
                <!-- 文章列表 -->
                <div class="posts-list">
                    <div class="post-item" v-for="post in recentPosts" :key="post.id">
                        <!-- 文章信息 -->
                        <div class="post-info">
                            <h4 class="post-title">{{ post.title }}</h4>
                            <p class="post-meta">
                                <span class="category">{{ post.categoryName }}</span>
                                <span class="date">{{ formatDate(post.createTime) }}</span>
                            </p>
                        </div>
                        <!-- 文章操作按钮 -->
                        <div class="post-actions">
                            <el-button size="small" @click="editPost(post.id)">编辑</el-button>
                            <el-button size="small" type="primary" @click="viewPost(post.id)">查看</el-button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 快速操作区域 -->
            <div class="quick-actions">
                <div class="section-header">
                    <h2>快速操作</h2>
                </div>
                <!-- 操作卡片网格 -->
                <div class="actions-grid">
                    <div class="action-card" v-for="action in quickActions" :key="action.title"
                        @click="handleQuickAction(action)">
                        <!-- 操作图标 -->
                        <div class="action-icon" :style="{ backgroundColor: action.color }">
                            <el-icon>
                                <component :is="action.icon" />
                            </el-icon>
                        </div>
                        <h3 class="action-title">{{ action.title }}</h3>
                        <p class="action-desc">{{ action.description }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
// 导入Vue 3 Composition API核心功能
import { ref, onMounted } from 'vue'
// 导入Vue Router用于页面导航
import { useRouter } from 'vue-router'
// 导入Element Plus图标组件和消息提示
import {
    Document,
    Folder,
    Collection,
    Link,
    ChatDotRound,
    Plus,
    Edit,
    Setting,
    Loading
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// 导入API工具函数和常量
import { get, API_PATHS } from '@/utils/api'

// 获取路由实例，用于页面跳转
const router = useRouter()

// 状态管理
const isUsingSampleData = ref(false)
const isLoading = ref(false)

// 类型定义
interface DashboardStats {
    articles: number
    categories: number
    tags: number
    friends: number
    comments: number
    visits: number
    change: {
        articles: string
        categories: string
        tags: string
        friends: string
    }
}

interface RecentPost {
    id: number
    title: string
    categoryName: string
    createTime: string
    views?: number
    likes?: number
    comments?: number
}

interface DashboardResponse {
    stats: DashboardStats
    recentPosts: RecentPost[]
}

// 示例数据
const sampleStats: DashboardStats = {
    articles: 25,
    categories: 8,
    tags: 32,
    friends: 15,
    comments: 128,
    visits: 15420,
    change: {
        articles: '+3 本周',
        categories: '+1 本周',
        tags: '+5 本周',
        friends: '+2 本周'
    }
}

const sampleRecentPosts: RecentPost[] = [
    {
        id: 1,
        title: 'Vue 3 组合式 API 详解',
        categoryName: '前端开发',
        createTime: '2024-12-19T10:30:00Z',
        views: 1250,
        likes: 89,
        comments: 12
    },
    {
        id: 2,
        title: 'TypeScript 高级类型指南',
        categoryName: '编程语言',
        createTime: '2024-12-18T14:20:00Z',
        views: 980,
        likes: 67,
        comments: 8
    },
    {
        id: 3,
        title: 'CSS Grid 布局完全指南',
        categoryName: '前端开发',
        createTime: '2024-12-17T09:15:00Z',
        views: 756,
        likes: 45,
        comments: 6
    }
]

// 使用示例数据的函数
const useSampleData = () => {
    isUsingSampleData.value = true
    statistics.value = [
        {
            title: '文章总数',
            value: sampleStats.articles,
            change: sampleStats.change.articles,
            trend: 'up',
            icon: 'Document',
            color: '#667eea'
        },
        {
            title: '分类总数',
            value: sampleStats.categories,
            change: sampleStats.change.categories,
            trend: 'up',
            icon: 'Folder',
            color: '#764ba2'
        },
        {
            title: '标签总数',
            value: sampleStats.tags,
            change: sampleStats.change.tags,
            trend: 'up',
            icon: 'Collection',
            color: '#f093fb'
        },
        {
            title: '友链总数',
            value: sampleStats.friends,
            change: sampleStats.change.friends,
            trend: 'up',
            icon: 'Link',
            color: '#4facfe'
        }
    ]
    recentPosts.value = sampleRecentPosts
}

// 统计数据数组 - 显示关键业务指标
const statistics = ref([
    {
        title: '文章总数',
        value: 0,
        change: '0 本周',
        trend: 'up',
        icon: 'Document',
        color: '#667eea'
    },
    {
        title: '分类总数',
        value: 0,
        change: '0 本周',
        trend: 'up',
        icon: 'Folder',
        color: '#764ba2'
    },
    {
        title: '标签总数',
        value: 0,
        change: '0 本周',
        trend: 'up',
        icon: 'Collection',
        color: '#f093fb'
    },
    {
        title: '友链总数',
        value: 0,
        change: '0 本周',
        trend: 'up',
        icon: 'Link',
        color: '#4facfe'
    }
])

// 最近文章列表数据
const recentPosts = ref<RecentPost[]>([])

// 快速操作配置数组
const quickActions = ref([
    {
        title: '新建文章',
        description: '创建一篇新的博客文章',
        icon: 'Plus',
        color: '#667eea',
        action: 'newPost'
    },
    {
        title: '管理分类',
        description: '添加或编辑文章分类',
        icon: 'Folder',
        color: '#764ba2',
        action: 'manageCategories'
    },
    {
        title: '管理标签',
        description: '添加或编辑文章标签',
        icon: 'Collection',
        color: '#f093fb',
        action: 'manageTags'
    },
    {
        title: '系统设置',
        description: '配置博客系统参数',
        icon: 'Setting',
        color: '#4facfe',
        action: 'settings'
    }
])

/**
 * 格式化日期显示
 * @param dateString - ISO格式的日期字符串
 * @returns 格式化后的本地日期字符串
 */
const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
}

/**
 * 编辑文章 - 跳转到文章编辑页面
 * @param id - 文章ID
 */
const editPost = (id: number) => {
    router.push(`/admin/posts/edit/${id}`)
}

/**
 * 查看文章 - 跳转到文章详情页面
 * @param id - 文章ID
 */
const viewPost = (id: number) => {
    router.push(`/blog-detail/${id}`)
}

/**
 * 处理快速操作点击事件
 * 根据操作类型跳转到相应的管理页面
 * @param action - 操作配置对象
 */
const handleQuickAction = (action: any) => {
    switch (action.action) {
        case 'newPost':
            // 跳转到新建文章页面
            router.push('/admin/posts/edit')
            break
        case 'manageCategories':
            // 跳转到分类管理页面
            router.push('/admin/categories')
            break
        case 'manageTags':
            // 跳转到标签管理页面
            router.push('/admin/tags')
            break
        case 'settings':
            // 跳转到系统设置页面
            router.push('/admin/settings')
            break
    }
}

/**
 * 获取统计数据
 * 从API获取仪表板所需的统计数据
 */
const fetchStatistics = async () => {
    isLoading.value = true
    try {
        const response = await get(API_PATHS.DASHBOARD.STATS, {
            timeout: 8000,
            retry: 2
        })
        
        if (response && response.success && response.data) {
            const data = response.data as DashboardResponse
            statistics.value = [
                {
                    title: '文章总数',
                    value: data.stats.articles,
                    change: data.stats.change.articles,
                    trend: 'up',
                    icon: 'Document',
                    color: '#667eea'
                },
                {
                    title: '分类总数',
                    value: data.stats.categories,
                    change: data.stats.change.categories,
                    trend: 'up',
                    icon: 'Folder',
                    color: '#764ba2'
                },
                {
                    title: '标签总数',
                    value: data.stats.tags,
                    change: data.stats.change.tags,
                    trend: 'up',
                    icon: 'Collection',
                    color: '#f093fb'
                },
                {
                    title: '友链总数',
                    value: data.stats.friends,
                    change: data.stats.change.friends,
                    trend: 'up',
                    icon: 'Link',
                    color: '#4facfe'
                }
            ]
            recentPosts.value = data.recentPosts
        }
    } catch (error) {
        ElMessage.error('获取统计数据失败')
        console.error('Error fetching statistics:', error)
        // 使用示例数据作为降级
        useSampleData()
    } finally {
        isLoading.value = false
    }
}

/**
 * 获取最近文章列表
 * 从API获取最近发布的文章
 */
const fetchRecentPosts = async () => {
    isLoading.value = true
    try {
        const response = await get(API_PATHS.DASHBOARD.RECENT_POSTS, {
            timeout: 8000,
            retry: 2
        })
        
        if (response && response.success && response.data) {
            const data = response.data as DashboardResponse
            recentPosts.value = data.recentPosts
        }
    } catch (error) {
        ElMessage.error('获取最近文章失败')
        console.error('Error fetching recent posts:', error)
        // 使用示例数据作为降级
        recentPosts.value = sampleRecentPosts
    } finally {
        isLoading.value = false
    }
}

// 组件挂载时获取初始数据
onMounted(() => {
    fetchStatistics()
})
</script>

<style scoped lang="scss">
// 导入仪表板页面样式
@use '../../assets/styles/admin/_dashboard';
</style>